<template>
  <main class="login-container">
    <n-form
      ref="loginFormRef"
      :model="user"
      :rules="rules"
      size="large"
      :label-width="80"
      label-placement="left"
      @submit.prevent="handleLogin"
    >
      <n-form-item path="name" label="账号">
        <n-input
          v-model:value="user.name"
          :input-props="{ autocomplete: 'username' }"
          autofocus
          placeholder="请输入账号"
        >
          <template #prefix>
            <n-icon :component="PersonOutline" />
          </template>
        </n-input>
      </n-form-item>
      
      <n-form-item path="password" label="密码">
        <n-input
          v-model:value="user.password"
          placeholder="请输入密码"
          :input-props="{ autocomplete: 'current-password' }"
          type="password"
          show-password-on="click"
        >
          <template #prefix>
            <n-icon :component="LockClosedOutline" />
          </template>
        </n-input>
      </n-form-item>
      
      <n-form-item>
        <n-button
          type="primary"
          size="large"
          class="w-full"
          attr-type="submit"
          :loading="loading"
        >
          {{ loading ? '登录中...' : '登录' }}
        </n-button>
      </n-form-item>
    </n-form>
  </main>
</template>

<script setup>
import { reactive, ref } from "vue";
import { PersonOutline, LockClosedOutline } from "@vicons/ionicons5";
// 假设您使用的是Naive UI
import { useMessage } from 'naive-ui'

/**
 * 导入存储
 */
import StorageService from "@/utils/dataStore";

/**
 * 请求状态
 */
import { requestedMessage } from "@/utils/asynchronous";

// 消息提示
const message = useMessage()
// 表单引用
const loginFormRef = ref(null)
// 加载状态
const loading = ref(false)

/**
 * 获取本地存储数据
 */
const localDataValue = StorageService.localData.name;

/**
 * 登录信息
 */
const user = reactive({
  name: localDataValue ?? "admin",
  password: "admin123",
});

// 表单校验规则
const rules = {
  name: {
    required: true,
    trigger: ['blur', 'input'],
    validator(rule, value) {
      if (!value || !value.trim().length) {
        return new Error("请输入账号");
      }
      return true;
    },
  },
  password: {
    required: true,
    trigger: ['blur', 'input'],
    validator: (rule, value) => {
      if (!value || !value.trim().length) {
        return new Error("请输入密码");
      }
      return true;
    },
  },
};

/**
 * 验证登录表单 通过后登录并保存 name 和 token，然后查询登录账号的权限做出对应跳转
 */
async function handleLogin() {
  try {
    // 验证表单
    await loginFormRef.value?.validate();
    
    // 设置加载状态
    loading.value = true;
    
    // 执行登录请求
    await requestedMessage(
      async () => {
        // 这里应该是实际的登录API调用
        // const response = await api.login(user);
        
        // 模拟登录成功
        const mockResponse = {
          name: user.name,
          token: 'mock_token_' + Date.now()
        };
        
        // 这里可以添加跳转逻辑
          //登录成功
        window.location.href = '/home'
        //保存信息
        // 保存数据到本地存储
        StorageService.saveToLocalStorage('token', mockResponse.token)
        // 保存数据到本地存储
        StorageService.saveToLocalStorage('userName', "管理员")

        return mockResponse;
      },
      {

        showSuccess: true,
        fullscreenLoading: true,
      }
    );
    
    message.success('登录成功');
  } catch (error) {
    console.log("登录异常", error);
    if (error.message) {
      message.error(error.message);
    }
  } finally {
    loading.value = false;
  }
}
</script>

<style scoped>
.login-container {
  max-width: 500px;
  margin: 0 auto;
  padding: 20px;
}

.w-full {
  width: 100%;
}
</style>